package com.zbcz.erp.activity

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.activity.viewModels
import androidx.core.content.ContextCompat
import androidx.core.widget.addTextChangedListener
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.alibaba.android.arouter.utils.TextUtils
import com.zbcz.erp.R
import com.zbcz.erp.adapter.CommonEditFileAdapter
import com.zbcz.erp.adapter.CommonEditFileAdapter.Companion.REMOTE_FILE_TYPE
import com.zbcz.erp.adapter.CustomSpinnerAdapter
import com.zbcz.erp.adapter.MyApplyToolsAdapter.Companion.MY_TOOLS_BEAN
import com.zbcz.erp.bean.BusinessAddBean
import com.zbcz.erp.bean.DictItem
import com.zbcz.erp.bean.DoneJobBean
import com.zbcz.erp.bean.FileItem
import com.zbcz.erp.bean.MyToolsBean
import com.zbcz.erp.databinding.ActivityApplyForSealBinding
import com.zbcz.erp.fragment.CommonListFragment.Companion.DONE_JOB_BEAN
import com.zbcz.erp.fragment.CommonListFragment.Companion.MY_APPLY
import com.zbcz.erp.fragment.CommonListFragment.Companion.MY_DONE_LIST
import com.zbcz.erp.fragment.CommonListFragment.Companion.MY_TO_DO_LIST
import com.zbcz.erp.fragment.CommonListFragment.Companion.RE_APPLY
import com.zbcz.erp.util.APPLY_FOR_SEAL
import com.zbcz.erp.util.DensityUtils
import com.zbcz.erp.util.IS_TEST_MODE
import com.zbcz.erp.util.ToastUtils
import com.zbcz.erp.util.UPLOAD_FORMAT_WHOLE
import com.zbcz.erp.util.formatDate
import com.zbcz.erp.util.formatDateTime
import com.zbcz.erp.util.onSingleClick
import com.zbcz.erp.util.showDatePickerDialog
import com.zbcz.erp.viewmodel.CommonRequestViewModel
import com.zbcz.erp.viewmodel.CommonRequestViewModel.Companion.DOCUMENT_TYPE
import com.zbcz.erp.viewmodel.CommonRequestViewModel.Companion.SEAL_TYPE
import java.io.File

/**
 * 用印申请活动
 */
@Route(path = APPLY_FOR_SEAL)
class ApplyForSealActivity : BaseActivity() {

    @Autowired(name = MY_TOOLS_BEAN)
    @JvmField
    var toolsBean: MyToolsBean? = null

    @Autowired(name = DONE_JOB_BEAN)
    @JvmField
    var mJobBean: DoneJobBean? = null

    @JvmField
    @Autowired
    var type: Int = 0

    companion object {
        const val TAG = "ApplyForSealActivity"

        fun convertDicItem(data: MutableList<DictItem>?): Array<DictItem>? {
            data?.add(0, DictItem("-1", "请选择", "", "请选择"))
            return data?.toTypedArray()
        }

        fun getDictText(data: MutableList<DictItem>?, value: String): String? {
            data?.forEach {
                if (it.value == value) {
                    return it.text
                }
            }
            return null
        }
    }

    private lateinit var mBinding: ActivityApplyForSealBinding
    private val mViewModel: CommonRequestViewModel by viewModels()
    private var mFormatTime: String? = null
    private var mFileAdapter: CommonEditFileAdapter? = null

    private var mDocTypeSpinnerAdapter: CustomSpinnerAdapter? = null

    private var mSealTypeSpinnerAdapter: CustomSpinnerAdapter? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mBinding = ActivityApplyForSealBinding.inflate(layoutInflater)
        setContentView(mBinding.root)
        ARouter.getInstance().inject(this)
        initViews()
        initUploadInfos()
        mViewModel.getDicItem(SEAL_TYPE)
        mViewModel.getDicItem(DOCUMENT_TYPE)
        mViewModel.mSealTypeDicItemLiveData.observe(this) {
            mSealTypeSpinnerAdapter = convertDicItem(it?.toMutableList())?.let { it1 ->
                CustomSpinnerAdapter(
                    this@ApplyForSealActivity, it1
                )
            }
            mBinding.spApplySealName.adapter = mSealTypeSpinnerAdapter
            if (mCurrentSealTypePos != 0) mBinding.spApplySealName.setSelection(mCurrentSealTypePos)

        }

        mViewModel.mDocTypeDicItemLiveData.observe(this) {
            mDocTypeSpinnerAdapter = convertDicItem(it?.toMutableList())?.let { it1 ->
                CustomSpinnerAdapter(
                    this@ApplyForSealActivity, it1
                )
            }
            mBinding.spApplySealFileType.adapter = mDocTypeSpinnerAdapter
            if (mCurrentDocTypePos != 0) mBinding.spApplySealFileType.setSelection(mCurrentDocTypePos)
        }
        mBinding.tvCancel.onSingleClick {
            finish()
        }
    }


    /**
     * 初始化视图
     */
    private fun initViews() {
        with(mBinding) {
            // 设置顶部边距
            clParent.setPadding(0, DensityUtils.dp2px(this@ApplyForSealActivity, 48f), 0, 0)
            clTitle.ivCommonBack.onSingleClick { finish() }
            clTitle.tvTitle.text = "用印申请"

            // 初始化文件适配器
            mFileAdapter = CommonEditFileAdapter(this@ApplyForSealActivity)
            rcFileList.adapter = mFileAdapter
            mFileAdapter?.submitList(listOf(FileItem(null, CommonEditFileAdapter.ADD_FILE_TYPE)))

            // 日期选择器
            tvApplySealDate.onSingleClick {
                showDatePickerDialog(this@ApplyForSealActivity) { year, month, dayOfMonth ->
                    tvApplySealDate.text = formatDate(year, month, dayOfMonth)
                    mFormatTime = formatDate(year, month, dayOfMonth, UPLOAD_FORMAT_WHOLE)
                    tvApplySealDate.setTextColor(
                        ContextCompat.getColor(
                            this@ApplyForSealActivity, R.color.black_text
                        )
                    )
                }
            }

            tvSealDateTop.onSingleClick {
                showDatePickerDialog(this@ApplyForSealActivity) { year, month, dayOfMonth ->
                    tvApplySealDate.text = formatDate(year, month, dayOfMonth)
                    mFormatTime = formatDate(year, month, dayOfMonth, UPLOAD_FORMAT_WHOLE)
                    tvApplySealDate.setTextColor(
                        ContextCompat.getColor(
                            this@ApplyForSealActivity, R.color.black_text
                        )
                    )
                }
            }
            // 提交按钮点击事件
            tvConfirm.onSingleClick {
                val mTargetFile = mFileAdapter?.getTargetFile(this@ApplyForSealActivity)
                onApplyConfirmClick(mTargetFile)
            }

            // 如果是测试模式，设置测试值
            if (IS_TEST_MODE) setTestValues()

            mBinding.edContentBrief.addTextChangedListener {
                val textSize = it.toString().length
                mBinding.tvBriefCount.text = "$textSize/300"
            }
            mBinding.edInputRemark.addTextChangedListener {
                val textSize = it.toString().length
                mBinding.tvRemarkCount.text = "$textSize/300"
            }

        }

        // 监听提交结果
        mViewModel.requestResult.observe(this) { pair ->
            if (pair.second == true) {
                ToastUtils.show("提交成功")
                finish()
            } else {
                ToastUtils.show(pair.first)
            }
        }
    }

    /**
     * 初始化上传信息
     */
    private fun initUploadInfos() {
        if (type == MY_TO_DO_LIST || type == MY_DONE_LIST || type == MY_APPLY || type == RE_APPLY) {
            if (type != RE_APPLY) {
                setFieldsEditable(false)
            }
            mViewModel.queryFormInfo(mJobBean?.tableId ?: "", mJobBean?.tableName ?: "")
            mViewModel.mQueryFormInfo.observe(this@ApplyForSealActivity) { addBean ->
                populateFormFields(addBean)
                if (type == RE_APPLY) {
                    if (addBean != null) {
                        displayReApplyViews(addBean)
                    }
                }
            }

            when (type) {
                MY_TO_DO_LIST -> displayToDoViews()
                MY_DONE_LIST, MY_APPLY -> displayDoneViews()
                //MY_APPLY -> displayReApplyViews()
            }
        }
    }

    /**
     * 显示重新申请视图
     */
    private fun displayReApplyViews(addBean: BusinessAddBean) {
        // 实现重新申请视图显示逻辑
        mBinding.tvApplySealDate.text = "请选择"
        mBinding.tvConfirm.onSingleClick {
            onReplyClick(addBean)
        }
        mBinding.tvCancel.onSingleClick {
            finish()
        }
    }


    /**
     * 显示待办视图
     */
    private fun displayToDoViews() {
        with(mBinding) {
            tvContentAdvice.visibility = View.VISIBLE
            edContentAdvice.visibility = View.VISIBLE
            tvAdviceCount.visibility = View.VISIBLE
            tvCancel.text = "驳回"
            tvConfirm.text = "同意"
            tvCancel.onSingleClick {
                onApplyConfirmClick(
                    mJobBean?.id ?: "", mJobBean?.procInstId ?: "", false
                )
            }
            tvConfirm.onSingleClick {
                onApplyConfirmClick(
                    mJobBean?.id ?: "", mJobBean?.procInstId ?: "", true
                )
            }

            mViewModel.mActPassLiveData.observe(this@ApplyForSealActivity) { result ->
                handleApprovalResult(result)
            }

            mViewModel.mActBackLiveData.observe(this@ApplyForSealActivity) { result ->
                handleRejectionResult(result)
            }

            edContentAdvice.addTextChangedListener { text ->
                val textSize = text.toString().length
                tvAdviceCount.text = "$textSize/100"
            }
        }
    }

    /**
     * 显示已完成视图
     */
    private fun displayDoneViews() {
        with(mBinding) {
            clBottomParent.visibility = View.GONE
            nsParent.setPadding(0, 0, 0, 0)
        }
    }

    /**
     * 处理审批结果
     */
    private fun handleApprovalResult(result: Pair<Boolean, String?>) {
        if (result.first) {
            ToastUtils.show("审批通过")
            finish()
        } else {
            ToastUtils.show(result.second ?: "")
        }
    }

    /**
     * 处理驳回结果
     */
    private fun handleRejectionResult(result: Pair<Boolean, String?>) {
        if (result.first) {
            ToastUtils.show("驳回成功")
            finish()
        } else {
            ToastUtils.show(result.second ?: "")
        }
    }


    private var mCurrentDocTypePos = 0
    private var mCurrentSealTypePos = 0

    /**
     * 填充表单字段
     */
    private fun populateFormFields(addBean: BusinessAddBean?) {
        with(mBinding) {
            edInputSealCount.setText(addBean?.number_of_copies.toString())
            edInputRemark.setText(addBean?.remarks)
            edContentBrief.setText(addBean?.content_summary)
            edInputResSealPerson.setText(addBean?.handler)
            edInputSendUnit.setText(addBean?.recipient_unit)
            tvApplySealDate.text = formatDateTime(addBean?.seal_date ?: "")
            mBinding.edInputResSealPerson.setText(if (!TextUtils.isEmpty(addBean?.handler)) addBean?.handler else "无")
            //addBean.sel
            addBean?.document_type?.toIntOrNull()?.let {
                spApplySealFileType.setSelection(it)
                mCurrentDocTypePos = it
            }
            addBean?.seal_type?.toIntOrNull()?.let {
                spApplySealName.setSelection(it)
                mCurrentSealTypePos = it
            }

            if (type != RE_APPLY) {
                tvApplySealDate.onSingleClick {
                    showDatePickerDialog(this@ApplyForSealActivity) { year, month, dayOfMonth ->
                        tvApplySealDate.text = formatDate(year, month, dayOfMonth)
                        mFormatTime = formatDate(year, month, dayOfMonth, UPLOAD_FORMAT_WHOLE)
                        tvApplySealDate.setTextColor(
                            ContextCompat.getColor(
                                this@ApplyForSealActivity, R.color.black_text
                            )
                        )
                    }
                }
            }
            tvApplySealDate.setTextColor(
                ContextCompat.getColor(
                    this@ApplyForSealActivity, R.color.black_text
                )
            )

            if (type != RE_APPLY) {
                if (!TextUtils.isEmpty(addBean?.file)) {
                    mFileAdapter?.submitList(
                        listOf(
                            FileItem(
                                uri = null, type = REMOTE_FILE_TYPE, remoteUrl = addBean?.file ?: ""
                            )
                        )
                    )
                } else {
                    tvFiles.visibility = View.GONE
                    llFileParent.visibility = View.GONE
                }
            } else {
                val mutableFileList = mutableListOf(FileItem(null, CommonEditFileAdapter.ADD_FILE_TYPE))
                if (!TextUtils.isEmpty(addBean?.file)) {
                    mutableFileList.add(
                        FileItem(
                            uri = null, type = REMOTE_FILE_TYPE, remoteUrl = addBean?.file ?: "", isDelAble = true
                        )
                    )
                }
                mFileAdapter?.submitList(mutableFileList)
            }
        }
    }

    /**
     * 设置字段是否可编辑
     */
    private fun setFieldsEditable(isEditable: Boolean) {
        with(mBinding) {
            edInputSealCount.isEnabled = isEditable
            edInputSealCount.isFocusable = isEditable
            edInputRemark.isEnabled = isEditable
            edInputRemark.isFocusable = isEditable
            edContentBrief.isEnabled = isEditable
            edContentBrief.isFocusable = isEditable
            edInputResSealPerson.isEnabled = isEditable
            edInputResSealPerson.isFocusable = isEditable
            tvApplySealDate.isEnabled = isEditable
//            tvApplySealName.isEnabled = isEditable
//            tvApplySealName.isFocusable = isEditable
            edInputSendUnit.isEnabled = isEditable
            edInputSendUnit.isFocusable = isEditable
            spApplySealFileType.isEnabled = false
            spApplySealName.isEnabled = false
        }
    }

    /**
     * 审批或驳回点击事件
     */
    private fun onApplyConfirmClick(id: String, procInstId: String, isPass: Boolean) {
        mViewModel.actPass(isPass, id, procInstId, mBinding.edContentAdvice.text.toString())
    }

    /**
     * 提交表单点击事件
     * 只适用新表单提交的情况
     */
    private fun onApplyConfirmClick(file: File?) {
        if (mFormatTime.isNullOrEmpty()) {
            ToastUtils.show("日期不能为空")
            return
        }
        val mDate = mFormatTime
        //val mName = mBinding.tvApplySealName.text.toString()
//        if (mName.isEmpty()) {
//            ToastUtils.show("名称不能为空")
//            return
//        }
        var mSealType = "1"
        mBinding.spApplySealName.selectedItem?.let {
            if (it is DictItem) {
                mSealType = it.value ?: ""
                if (TextUtils.isEmpty(it.value) || it.value == "-1") {
                    ToastUtils.show("请选择印章类型")
                    return
                }
            }
        }

        var mFileType = "1"
        mBinding.spApplySealFileType.selectedItem?.let {
            if (it is DictItem) {
                mFileType = it.value ?: ""
                if (TextUtils.isEmpty(it.value) || it.value == "-1") {
                    ToastUtils.show("请选择文件类型")
                    return
                }
            }
        }
        val mSendUnit = mBinding.edInputSendUnit.text.toString()
        val mBrief = mBinding.edContentBrief.text.toString()
        val mCount = mBinding.edInputSealCount.text.toString()
        val mResSealPerson = mBinding.edInputResSealPerson.text.toString()
        val mRemark = mBinding.edInputRemark.text.toString()
        //if (toolsBean != null) toolsBean?.id else mJobBean.id
        val mAddBean = BusinessAddBean().apply {
            content_summary = mBrief
            seal_name = mSealType
            createTime = mDate
            document_type = mFileType
            recipient_unit = mSendUnit
            number_of_copies = mCount
            remarks = mRemark
            seal_date = mDate
            handler = mResSealPerson
            id = toolsBean?.id
            name = toolsBean?.name
            procDeTitle = toolsBean?.name
            procDefId = toolsBean?.id
            tableName = BusinessAddBean.SEAL_TABLE
            file_handler = mResSealPerson
//            id = if (toolsBean != null) toolsBean?.id else mJobBean?.procInstId
//            name = if (toolsBean != null) toolsBean?.name else mJobBean?.name
//            procDeTitle = if (toolsBean != null) toolsBean?.name else mJobBean?.name
//            procDefId = if (toolsBean != null) toolsBean?.id else mJobBean?.procInstId
        }
        setTestValues()
        mViewModel.createRequest(mAddBean, file)
    }

    /**
     * 设置测试值
     */
    private fun setTestValues() {
        if (IS_TEST_MODE) {
            with(mBinding) {
//                tvApplySealName.setText("test name")
//                tvApplySealFileType.setText("2")
                edInputSendUnit.setText("666")
                edContentBrief.setText("mBrief")
                edInputSealCount.setText("1")
                edInputResSealPerson.setText("zhangsan")
                edInputRemark.setText("remark")
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == ErpWorkProcessActivity.REQUEST_CODE_OPEN_DOCUMENT && resultCode == RESULT_OK) {
            data?.data?.let { fileUri ->
                Log.d(ErpWorkProcessActivity.TAG, fileUri.toString())
                mFileAdapter?.addData(fileUri)
            }
        }
    }

    private fun onReplyClick(addBean: BusinessAddBean) {
        if (mFormatTime.isNullOrEmpty()) {
            ToastUtils.show("日期不能为空")
            return
        }
        val mDate = mFormatTime
        val mDocType = mBinding.spApplySealFileType.selectedItem
        val mSendUnit = mBinding.edInputSendUnit.text.toString()
        val mBrief = mBinding.edContentBrief.text.toString()
        val mCount = mBinding.edInputSealCount.text.toString()
        val mResSealPerson = mBinding.edInputResSealPerson.text.toString()
        val mRemark = mBinding.edInputRemark.text.toString()
        addBean.apply {
            content_summary = mBrief
            //seal_name = mName
            createTime = mDate
            //document_type = mFileType
            recipient_unit = mSendUnit
            number_of_copies = mCount
            remarks = mRemark
            seal_date = mDate
            handler = mResSealPerson
            file_handler = mResSealPerson
        }
        mViewModel.createEditRequest(addBean, mFileAdapter?.getTargetFile(this), mJobBean?.id)
    }
}
